package com.longxi.tianjintianbao.ui.presenter.maintain;

import android.content.Intent;
import android.util.Log;

import com.alibaba.fastjson.JSONObject;
import com.longxi.tianjintianbao.AppConst;
import com.longxi.tianjintianbao.R;
import com.longxi.tianjintianbao.api.ApiRetrofit;
import com.longxi.tianjintianbao.api.response.BaseResponse;
import com.longxi.tianjintianbao.exception.ExceptionHandle;
import com.longxi.tianjintianbao.exception.MySubscriber;
import com.longxi.tianjintianbao.greedao.controller.DataPatrolController;
import com.longxi.tianjintianbao.greedao.entity.Patrol;
import com.longxi.tianjintianbao.greedao.upload.UploadPatrol;
import com.longxi.tianjintianbao.ui.adapter.MaintainListPagerAdapter;
import com.longxi.tianjintianbao.ui.base.BaseActivity;
import com.longxi.tianjintianbao.ui.base.BasePresenter;
import com.longxi.tianjintianbao.ui.fragment.maintain.MaintainListFragment;
import com.longxi.tianjintianbao.ui.view.maintain.IMaintainListAtView;
import com.longxi.tianjintianbao.utils.LogUtils;
import com.longxi.tianjintianbao.utils.MyUtils;

import java.util.ArrayList;
import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class MaintainListAtPresenter extends BasePresenter<IMaintainListAtView> {

    private MaintainListPagerAdapter maintainListPagerAdapter;
    private Intent intent = new Intent();
    public long count = 0;//有多少未上传数据

    private void initVariable() {
        mCategoryList = new ArrayList<>();
        mCategoryList.add("今日");
        mCategoryList.add("本周");
        mCategoryList.add("本月");
//        mCategoryList.add("历史");
    }

    //tab 标签页
    private List<String> mCategoryList;

    public List<String> getCategoryList() {
        if (mCategoryList == null) {
            mCategoryList = new ArrayList<>();
        }
        return mCategoryList;
    }

    public MaintainListAtPresenter(BaseActivity context) {
        super(context);
    }

    public void setBar() {
        mContext.setTitle("保养");
        mContext.setTvLeft(MyUtils.getString(R.string.home));
        setUINoUploadData();
        initVariable();
    }

    /**
     * 更新一下数据 并且将上传数据按钮显示出来
     */
    public void setUINoUploadData() {
        count = DataPatrolController.isUploadData();
        if(count > 0){
            mContext.setIvRight(R.mipmap.ic_data_upload);
        }
    }

    public void initViewPager(){
        maintainListPagerAdapter = new MaintainListPagerAdapter(mContext.getSupportFragmentManager(), getCategoryList());
        getView().getViewPager().setAdapter(maintainListPagerAdapter);
        getView().getViewPager().setOffscreenPageLimit(getCategoryList().size() - 1);
        getView().getTabLayout().setViewPager(getView().getViewPager());
        getView().getTabLayout().setTabSpaceEqual(true);
        if(count != 0){
            getView().getTabLayout().showMsg(1, (int) count);
            getView().getTabLayout().setMsgMargin(1, 0, 10);
        }
    }

    public void refreshFragmentUi() {
        MaintainListFragment maintainListFragment = (MaintainListFragment) maintainListPagerAdapter.getCurrentFragment();
        maintainListFragment.refreshReceiptList();
        sendBroadcast();
    }

    boolean isUpload = false;
    public void saveInspection() {
        if(isUpload){
            MyUtils.showToast("正在上传，请勿重复点击");
            return;
        }
        isUpload = true;
        mContext.showWaitingDialog(MyUtils.getString(R.string.upload));
        List<Patrol> patrolList = DataPatrolController.getUploadList();
        if(patrolList.size() == 0){
            mContext.hideWaitingDialog();
            MyUtils.showToast("无需要上传的数据");
            return;
        }

        List<UploadPatrol> uploadPatrolList = new ArrayList<>();
        for (Patrol patrol : patrolList) {
            uploadPatrolList.add(new UploadPatrol(patrol.getUserid(), patrol.getBillid(), patrol.getApplicant(), patrol.getState(), patrol.getExplain(), patrol.getReleasetime(), MyUtils.imageToBase64(patrol.getImage1()), MyUtils.imageToBase64(patrol.getImage2())));
        }

        LogUtils.d("uploadPatrol", JSONObject.toJSONString(uploadPatrolList));

        ApiRetrofit.getInstance().saveInspection(JSONObject.toJSONString(uploadPatrolList))
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<BaseResponse>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mContext.hideWaitingDialog();
                MyUtils.showToast(throwable.message);
                isUpload = false;//可以上传
            }

            @Override
            public void onNext(BaseResponse baseResponse) {
                mContext.hideWaitingDialog();
                isUpload = false;//可以上传
                if(baseResponse.getCode() != 0){
                    MyUtils.showToast(baseResponse.getMsg());
                    return;
                }
                DataPatrolController.updateAllByIsDraft();
                setUINoUploadData();
                getView().getTabLayout().showMsg(1, (int) count);
                getView().getTabLayout().setMsgMargin(1, 0, 10);
                sendBroadcast();
                mContext.hideWaitingDialog();
                MyUtils.showToast("提交成功");
            }
        });
    }

    /**
     * 发送广播
     */
    public void sendBroadcast(){
        //设置广播的名字（设置Action）
        intent.setAction(AppConst.REFRESH_HOME_FRAGMENT);
        //携带数据
        //intent.putExtra("refreshPatrolCount",true);
        //发送广播（无序广播）
        mContext.sendBroadcast(intent);
    }
}
